// components/Active.jsx
import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from '../css/actives.module.css';
import backimg from '../assets/backimg.png';
import right from '../assets/right.png';
import back from "../assets/left.png";
import hourse3 from "../assets/hourse3.png";
import { imgUrl } from '../config'; // 导入imgUrl
import {
  getWinningRecords,
  getPrizeData,
  getActiveData,
  submitWinningResult,
} from '../api/active';

const Active = () => {
  // 从 sessionStorage 中获取用户 ID 并存储在 state 中
  const [userid, setUserid] = useState(null);
  // 中奖奖品名称
  const [names, setNames] = useState('');
  // 中奖记录数据
  const [data, setData] = useState([]);
  // 奖品数据
  const [prizeData, setPrizeData] = useState([]);
  // 活动数据
  const [activeData, setActiveData] = useState([]);
  // 用于页面导航
  const navigate = useNavigate();

  // 新抽奖逻辑的状态
  // 当前选中的奖品索引
  const [activeIndex, setActiveIndex] = useState(-1);
  // 抽奖是否正在进行
  const [isRolling, setIsRolling] = useState(false);
  // 抽奖结果
  const [result, setResult] = useState(null);
  // 中奖弹窗是否可见
  const [isPrizeModalVisible, setIsPrizeModalVisible] = useState(false);
  // 攻略弹窗是否可见
  const [isStrategyModalVisible, setIsStrategyModalVisible] = useState(false);
  // 暂停选中奖品弹窗是否可见
  const [isPauseModalVisible, setIsPauseModalVisible] = useState(false);
  // 用于控制抽奖滚动的定时器引用
  const rollInterval = useRef(null);
  // 用于存储奖品项的引用
  const prizeItemsRef = useRef([]);

  // 顺时针顺序的索引数组（九宫格布局）
  const clockwiseOrder = [0, 1, 2, 5, 8, 7, 6, 3];

  // 获取中奖记录的函数
  const fetchWinningRecords = async () => {
    try {
      // 调用 api 获取中奖记录
      const response = await getWinningRecords(108);
      console.log('中奖记录接口响应数据:', response);
      // 设置中奖记录数据
      setData(response.data || []);
    } catch (error) {
      console.error('获取中奖记录失败:', error);
    }
  };

  // 组件挂载和更新时的副作用函数
  useEffect(() => {
    // 从 sessionStorage 中获取用户 ID
    const id = JSON.parse(sessionStorage.getItem("userid"));
    setUserid(id);
    // 获取中奖记录
    fetchWinningRecords();
    // 获取奖品数据
    fetchPrizeData();
    // 获取活动数据
    fetchActiveData();
    return () => {
      // 清除定时器
      if (rollInterval.current) {
        clearTimeout(rollInterval.current);
      }
    };
  }, []);

  // 开始抽奖的函数
  const startLottery = () => {
    // 如果抽奖正在进行或活动数据为空，则不进行操作
    if (isRolling || activeData.length === 0) return;

    setIsRolling(true);
    setResult(null);
    setActiveIndex(-1);

    const startTime = Date.now();
    const endTime = startTime + 6000; // 6 秒后结束
    const finalIndex = Math.floor(Math.random() * activeData.length);

    const roll = () => {
      const currentTime = Date.now();
      if (currentTime >= endTime) {
        clearInterval(rollInterval.current);
        setIsRolling(false);
        const prize = activeData[finalIndex];
        setResult(prize);
        setNames(prize.name);
        setActiveIndex(finalIndex);
        showPrizeResult(prize);
        return;
      }

      setActiveIndex(prev => {
        const nextIndex = (prev + 1) % activeData.length;
        return nextIndex;
      });

      rollInterval.current = setTimeout(roll, 100);
    };

    roll();
  };

  // 停止抽奖的函数
  const stopLottery = () => {
    if (rollInterval.current) {
      clearTimeout(rollInterval.current);
      setIsRolling(false);
      const currentPrize = activeData[activeIndex];
      if (currentPrize) {
        console.log('暂停时选中的奖品:', currentPrize);
        setNames(currentPrize.name);
        setIsPauseModalVisible(true);
        updateRecordList(currentPrize);
      }
    }
  };

  // 显示中奖结果的函数
  const showPrizeResult = (prize) => {
    // 打印选中的奖品
    console.log('选中的奖品:', prize);
    // 显示中奖弹窗
    setIsPrizeModalVisible(true);
    updateRecordList(prize);
  };

  // 更新中奖记录列表的函数
  const updateRecordList = (prize) => {
    const newRecord = {
      nickname: '用户昵称',
      name: prize.name,
      create_time: new Date().toLocaleString()
    };
    // 更新中奖记录数据
    setData([newRecord, ...data]);
  };

  // 确认中奖的函数
  const confirmPrize = async () => {
    if (!names) return;

    try {
      // 提交中奖结果
      const response = await submitWinningResult({
        user_id: userid,
        scenic_id: 3,
        active_id: 2,
        status: 2,
        name: names,
        img: '',
      });
      console.log(response);
      // 隐藏中奖弹窗
      setIsPrizeModalVisible(false);
      // 重新获取中奖记录
      fetchWinningRecords();
    } catch (error) {
      console.error("提交中奖结果失败:", error);
    }
  };

  // 确认暂停选中奖品的函数
  const confirmPausePrize = () => {
    setIsPauseModalVisible(false);
  };

  // 获取奖品数据的函数
  const fetchPrizeData = async () => {
    try {
      // 调用 api 获取奖品数据
      const response = await getPrizeData(2);
      const prizeItems = response.data?.slice(0, 9) || [];
      // 设置奖品数据
      setPrizeData(prizeItems);
    } catch (error) {
      console.error('获取奖品数据失败:', error);
    }
  };

  // 获取活动数据的函数
  const fetchActiveData = async () => {
    try {
      // 调用 api 获取活动数据
      const response = await getActiveData(2);
      const prizeItems = response.data?.slice(0, 8) || [];
      console.log(response, "活动列表");
      // 设置活动数据
      setActiveData(prizeItems);
    } catch (error) {
      console.error('获取活动数据失败:', error);
    }
  };

  // 图片加载错误处理函数
  const handleImageError = (e) => {
    e.target.src = backimg;
  };

  // 返回上一页的函数
  const left = () => navigate(-1);
  // 跳转首页的函数
  const first = () => navigate('/home');

  return (
    <div className={styles.container}>
      {/* 顶部 */}
      <div className={styles.top}>
        <div style={{ display: "flex", alignItems: "center", whiteSpace: "nowrap", width: "50%", justifyContent: "space-between" }}>
          <div className={styles.lefts}>
            <img src={back} alt="" onClick={left} />
            <div className={styles.line}></div>
            <img id="hourse" src={hourse3} alt="" onClick={first} />
          </div>
        </div>
        <p>活动</p>
      </div>
      <div className={styles.activetime}></div>
      {/* 背景图 */}
      <img className={styles.backgroundImage} src={backimg} alt="" />

      {/* 抽奖区域 */}
      <div className={styles.gridContainerDiv}>
        <div style={{ marginTop: '-15%', position: 'absolute', width: '100%', textAlign: 'center', color: '#AA0401', fontWeight: '700', fontSize: '12px' }}>2025-03-11——2025-04-21</div>
        <div className={styles.gridContainer}>
          {Array(9).fill(0).map((_, index) => {
            // 中心位置不显示按钮
            if (index === 4) {
              return <div key={index}></div>;
            }
            // 获取对应的奖品索引
            const prizePos = clockwiseOrder.indexOf(index);
            const prize = prizePos !== -1 ? activeData[prizePos] : null;
            return (
              <div
                key={index}
                ref={(el) => {
                  if (el && prizePos !== -1) prizeItemsRef.current[prizePos] = el;
                }}
                className={`${styles.prizeItem} ${prizePos === activeIndex ? styles.active : ''
                  }`}
              >
                {prize && (
                  <>
                    <img
                      className={styles.image}
                      src={`${imgUrl}${prize.img}`} 
                      onError={handleImageError}
                      alt="奖品图片" 
                    />
                    <p>{prize.name}</p>
                  </>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* 查看攻略 */}
      <div className={styles.bodybottom}>
        <p style={{ marginTop: '100px' }} className={styles.Strategy} onClick={() => {
          setIsStrategyModalVisible(true);
        }}>查看攻略</p>
        <button className={styles.pause} onClick={stopLottery} disabled={!isRolling}>暂停</button>
        <button className={styles.begin} onClick={startLottery} disabled={isRolling}>开始</button>

        <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
          <p style={{ marginTop: '100px' }} className={styles.geng} onClick={() => navigate('/awardItem')}>更多</p>
          {/* <img src={right} alt="" style={{ width: "24px", height: "19px", marginTop: "1px" }} /> */}
        </div>

      </div>

      {/* 中奖记录 */}
      <div className={styles.recordsContainer}>
        <div className={styles.recordsTitle}>中奖记录</div>
        {/* 表头 */}
        <div className={styles.recordsHeader}>
          <div className={styles.headerCell}>序号</div>
          <div className={styles.headerCell}>昵称</div>
          <div className={styles.headerCell}>奖品</div>
          <div className={styles.headerCell}>时间</div>
        </div>

        {/* 记录列表 */}
        <div className={styles.recordsList}>
          {Array.isArray(data) && data.map((item, index) => (
            <div key={index} className={styles.recordRow}>
              <div className={styles.recordCell}>{index + 1}</div>
              <div className={styles.recordCell}>{item.nickname}</div>
              <div className={styles.recordCell}>{item.name}</div>
              <div className={styles.recordCell}>{item.create_time}</div>
            </div>
          ))}
        </div>
      </div>

      {/* 阴影 */}
      <div className={`${styles.masks} ${styles.left}`}>
        <div className={styles.acitvecon}></div>
      </div>

      {/* 中奖弹窗 */}
      {isPrizeModalVisible && (
        <div className={styles.prizeModal}>
          <div className={styles.prizeModalContent}>
            <p className={styles.prizeModalTitle}>恭喜抽中 {names}</p>
            <button className={styles.prizeModalButton} onClick={confirmPrize}>确定</button>
          </div>
        </div>
      )}

      {/* 攻略弹窗 */}
      {isStrategyModalVisible && (
        <div className={styles.strategyModal}>
          <h3>活动流程</h3>
          <div className={styles.contentchild}>523</div>
          <div className={styles.contentchildone}>
            <div className={styles.quxiao} onClick={() => setIsStrategyModalVisible(false)}>取消</div>
            <div className={styles.confirm} onClick={() => setIsStrategyModalVisible(false)}>我已阅读</div>
          </div>
        </div>
      )}

      {/* 暂停选中奖品弹窗 */}
      {isPauseModalVisible && (
        <div className={styles.prizeModal}>
          <div className={styles.prizeModalContent}>
            <p className={styles.prizeModalTitle}>暂停时选中的奖品为 {names}</p>
            <button className={styles.prizeModalButton} onClick={confirmPausePrize}>确定</button>
          </div>
        </div>
      )}
    </div>
  );
};

export default Active;